#! /bin/bash

MY_PATH=/opt/rgrub
LINE_NUM=

mkdir -p $MY_PATH
cp etc_default_grub /etc/default/grub
update-grub
cp /boot/grub/grub.cfg $MY_PATH
cp ip_port $MY_PATH
cp remote_grub.sh $MY_PATH

###
LINE_NUM=`awk '/menuentry /{print NR;exit}' $MY_PATH/grub.cfg`
LINE_NUM=`expr $LINE_NUM - 1`
sed "1,${LINE_NUM}d" "$MY_PATH/grub.cfg" > "$MY_PATH/grub.cfg.1"
#echo $LINE_NUM
line=
be_quit=
echo "menuentry 'rgrub' {" > "$MY_PATH/grub.cfg.2"
while IFS='' read -r line || [[ -n "$line" ]]; do
	if [[ "$line" =~ "initrd" || "$line" =~ "initrd16" ]]; then 
		be_quit='y'
		echo "set which=rgrub" >> "$MY_PATH/grub.cfg.2"
		echo "save_env which" >> "$MY_PATH/grub.cfg.2"
	fi	
	if [[ "$line" =~ "}" && -n "$be_quit" ]]; then
		echo "$line" >> "$MY_PATH/grub.cfg.2"
		break
	fi
	if [[ "$line" =~ "menuentry" || "$line" =~ "load_video" || "$line" =~ "gfxmode" ]]; then
		continue;
	fi
	if [[ "$line" =~ "linux" || "$line" =~ "linux16" ]]; then
		echo "$line" text >> "$MY_PATH/grub.cfg.2"
		continue;
	fi
	echo "$line" >> "$MY_PATH/grub.cfg.2"
done < "$MY_PATH/grub.cfg.1"

echo "RGrub MenuEntry:"
echo 
cat "$MY_PATH/grub.cfg.2"

LINE_NUM=`awk "/menuentry 'rgrub'/{print NR;exit}" /etc/grub.d/40_custom`
if [[ -n "$LINE_NUM" ]]; then
	sed -i "${LINE_NUM},/-End/d" /etc/grub.d/40_custom
fi
cat "$MY_PATH/grub.cfg.2" >> /etc/grub.d/40_custom

grep 'menuentry ' /boot/grub/grub.cfg | cut -d "'" -f2 > "$MY_PATH/rgrub.cfg"

#sed -i -e '$i \exec ${MY_PATH}/remote_grub.sh \n' /etc/rc.local
grep remote_grub.sh /etc/rc.local
[[ $? == 0 ]] || sed -i -e '$i \exec /opt/rgrub/remote_grub.sh \n' /etc/rc.local

update-grub
#replace ，with ,
sed -i 's/，/,/g' /opt/rgrub/rgrub.cfg
sed -i 's/，/,/g' /boot/grub/grub.cfg

grub-editenv create
grub-set-default rgrub
